package com.onlyxiahui.aware.extend.shardingsphere.algorithm;

import java.nio.charset.StandardCharsets;
import java.util.Collection;

import com.google.common.hash.Hashing;
import com.onlyxiahui.aware.extend.shardingsphere.algorithm.util.ShardingHandlerUtil;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

/**
 * Hash一致性分片<br>
 * Date 2019-08-26 10:57:11<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class ConsistentHashPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Comparable<?>> {

	@Override
	public String doSharding(
			final Collection<String> databaseNames,
			final PreciseShardingValue<Comparable<?>> shardingValue) {
		// 当前数据节点数量
		int size = databaseNames.size();
		if (size == 1) {
			return databaseNames.iterator().next();
		}

		Comparable<?> value = shardingValue.getValue();
		String text = value.toString();
		// 计算当前分片值所在的节点号
		int nodeNumber = Hashing.consistentHash(Hashing.sha256().hashString(text, StandardCharsets.UTF_8), size);

		// 找到匹配的数据库名称并返回
		for (String databaseName : databaseNames) {
			if (ShardingHandlerUtil.eq(databaseName, nodeNumber)) {
				return databaseName;
			}
		}
		throw new RuntimeException("数据分片异常");
	}
}
